<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-minimal.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"shu_kang.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="NIO学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="NIO学习笔记">
<meta property="og:url" content="http://shu_kang.gitee.io/2021/08/15/NIO/index.html">
<meta property="og:site_name" content="Shuker的学习小屋">
<meta property="og:description" content="NIO学习笔记">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210304154740636.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210304160134306.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/.%5Cimg%5Cimage-20210304161656188.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305115457597.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305122308563.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210304170527506.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/.%5Cimg%5Cimage-20210305121932875.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305142054115.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305143138279.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210304173004802.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305163213213.png">
<meta property="og:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210305162501149.png">
<meta property="article:published_time" content="2021-08-14T16:00:00.000Z">
<meta property="article:modified_time" content="2021-08-15T09:53:14.901Z">
<meta property="article:author" content="Shuker">
<meta property="article:tag" content="IO流">
<meta property="article:tag" content="网络编程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://shu_kang.gitee.io/2021/08/15/NIO/img/image-20210304154740636.png">

<link rel="canonical" href="http://shu_kang.gitee.io/2021/08/15/NIO/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>NIO学习笔记 | Shuker的学习小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="Shuker的学习小屋" type="application/atom+xml">
</head>

<!-- ��̬���� -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>



<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://your-url" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Shuker的学习小屋</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://shu_kang.gitee.io/2021/08/15/NIO/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://pic1.zhimg.com/50/v2-e6c265da0c4d51976b5a4f5789bf1930_qhd.jpg?source=ba7200d9">
      <meta itemprop="name" content="Shuker">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Shuker的学习小屋">
    </span>
      <header class="post-header">
        
	  <i class="fa fa-thumb-tack"></i>
	  <font color=7D26CD>置顶</font>
	
        <h1 class="post-title" itemprop="name headline">
          NIO学习笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-15 00:00:00 / 修改时间：17:53:14" itemprop="dateCreated datePublished" datetime="2021-08-15T00:00:00+08:00">2021-08-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <div class="post-description">NIO学习笔记</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="NIO"><a href="#NIO" class="headerlink" title="NIO"></a>NIO</h1><h2 id="1-什么是NIO"><a href="#1-什么是NIO" class="headerlink" title="1. 什么是NIO"></a>1. 什么是NIO</h2><h4 id="IO回顾"><a href="#IO回顾" class="headerlink" title="IO回顾"></a>IO回顾</h4><ul>
<li>IO：Input OutPut（输入 输出）</li>
<li>IO技术的作用：解决设备和设备之间的数据传输问题</li>
<li>IO的应用场景：图片上传、下载、打印机打印信息表、解析XML…</li>
</ul>
<h4 id="1-1-概念"><a href="#1-1-概念" class="headerlink" title="1.1 概念"></a>1.1 概念</h4><ul>
<li>即 <code>Java New IO</code></li>
<li>是1个全新的、 <code>JDK 1.4</code>后提供的 <code>IO API</code></li>
<li>Java API中提供了两套NIO，一套是针对<code>标准输入输出NIO</code>，另一套就是<code>网络编程NIO</code></li>
</ul>
<h4 id="1-2-作用"><a href="#1-2-作用" class="headerlink" title="1.2 作用"></a>1.2 作用</h4><ul>
<li><code>NIO</code>和<code>IO</code>有相同的作用和目的，但实现方式不同</li>
<li>可替代 标准<code>Java IO</code> 的<code>IO API</code></li>
<li>IO是以<strong>流</strong>的方式处理数据，而NIO是以<strong>块</strong>的方式处理数据。</li>
</ul>
<h4 id="1-3-流与块的比较"><a href="#1-3-流与块的比较" class="headerlink" title="1.3 流与块的比较"></a>1.3 流与块的比较</h4><ul>
<li><p>NIO和IO最大的区别是数据打包和传输方式。</p>
</li>
<li><p>IO是以<strong>流</strong>的方式处理数据，而NIO是以<strong>块</strong>的方式处理数据。</p>
</li>
</ul>
<p><strong>面向流</strong>的IO一次一个字节的处理数据，一个输入流产生一个字节，一个输出流就消费一个字节。</p>
<p><strong>面向块</strong>的IO系统以块的形式处理数据。每一个操作都在一步中产生或消费一个数据块。按块要比按流快的多</p>
<p>（举例：拿水龙头来比喻：流就像水龙头滴水，每次只有一滴；块就像水龙头往水壶放水，放满之后对一整个水壶的水进行操作）</p>
<h4 id="1-4-新特性"><a href="#1-4-新特性" class="headerlink" title="1.4 新特性"></a>1.4 新特性</h4><p>对比于 <code>Java IO</code>，<code>NIO</code>具备的新特性如下：</p>
<img src=".\img\image-20210304154740636.png" alt="image-20210304154740636" style="zoom:67%;" />

<ul>
<li><p>可简单认为：<strong>IO是面向流的处理，NIO是面向块(缓冲区)的处理</strong></p>
<ul>
<li>面向流的I/O 系统<strong>一次一个字节地处理数据</strong></li>
</ul>
<ul>
<li>一个面向块(缓冲区)的I/O系统<strong>以块的形式处理数据</strong></li>
</ul>
</li>
</ul>
<h4 id="1-5-核心组件"><a href="#1-5-核心组件" class="headerlink" title="1.5 核心组件"></a>1.5 核心组件</h4><p><code>Java NIO</code>的核心组件 包括：</p>
<ul>
<li>通道（<code>Channel</code>）</li>
<li>缓冲区（<code>Buffer</code>）</li>
<li>选择器（<code>Selector</code>）</li>
</ul>
<p>在NIO中并不是以流的方式来处理数据的，而是以buffer缓冲区和Channel管道<strong>配合使用</strong>来处理数据。</p>
<p>Selector是因为NIO可以使用异步的非阻塞模式才加入的东西</p>
<img src=".\img\image-20210304160134306.png" alt="image-20210304160134306" style="zoom:67%;" />

<p>简单理解一下：</p>
<ul>
<li>Channel管道比作成铁路，buffer缓冲区比作成火车(运载着货物)</li>
</ul>
<p>​        而我们的NIO就是<strong>通过Channel管道运输着存储数据的Buffer缓冲区的来实现数据的处理</strong>！</p>
<ul>
<li><p>要时刻记住：Channel不与数据打交道，它只负责运输数据。与数据打交道的是Buffer缓冲区</p>
</li>
<li><ul>
<li><strong>Channel–&gt;运输</strong></li>
<li><strong>Buffer–&gt;数据</strong></li>
</ul>
</li>
</ul>
<p>相对于传统IO而言，<strong>流是单向的</strong>。对于NIO而言，有了Channel管道这个概念，我们的<strong>读写都是双向</strong>的(铁路上的火车能从广州去北京、自然就能从北京返还到广州)！</p>
<h2 id="2-Buffer缓冲区"><a href="#2-Buffer缓冲区" class="headerlink" title="2. Buffer缓冲区"></a>2. Buffer缓冲区</h2><h4 id="2-1-Buffer缓冲区概述"><a href="#2-1-Buffer缓冲区概述" class="headerlink" title="2.1 Buffer缓冲区概述"></a>2.1 Buffer缓冲区概述</h4><p>作用：缓冲区，用来存放具体要被传输的数据，比如文件、scoket 等。这里将数据装入 Buffer 再通过通道进行传输。</p>
<p>Buffer 就是一个数组，用来保存不同数据类型的数据</p>
<p>在 NIO 中，所有的缓冲区类型都继承于抽象类 Buffer，最常用的就是 ByteBuffer，对于 Java 中的基本类型，基本都有一个具体 Buffer 类型与之相对应，它们之间的继承关系如下图所示</p>
<p><img src=".%5Cimg%5Cimage-20210304161656188.png" alt="image-20210304161656188"></p>
<ul>
<li>ByteBuffer：存储字节数据到缓冲区</li>
<li>ShortBuffer：存储字符串数据到缓冲区</li>
<li>CharBuffer： 存储字符数据到缓冲区</li>
<li>IntBuffer：存储整数数据到缓冲区</li>
<li>LongBuffer：存储长整型数据到缓冲区</li>
<li>DoubleBuffer：存储小数到缓冲区</li>
<li>FloatBuffer：存储小数到缓冲区</li>
</ul>
<p>对于 Java 中的基本数据类型，都有一个 Buffer 类型与之相对应，最常用的自然是<strong>ByteBuffer</strong> 类（二进制数据）</p>
<h4 id="2-2-ByteBuffer的创建方式"><a href="#2-2-ByteBuffer的创建方式" class="headerlink" title="2.2 ByteBuffer的创建方式"></a>2.2 ByteBuffer的创建方式</h4><p>代码演示</p>
<ul>
<li><p>在堆中创建缓冲区：allocate(int capacity)</p>
</li>
<li><p>在系统内存创建缓冲区：allocateDirect(int capacity)</p>
</li>
<li><p>通过普通数组创建缓冲区：wrap(byte[] arr)</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo01Buffer</span>创建方式 </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//在堆中创建缓冲区：allocate(int capacity)*</span></span><br><span class="line">        ByteBuffer buffer1 = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//在系统内存创建缓冲区：allocateDirect(int capacity)</span></span><br><span class="line">        ByteBuffer buffer2 = ByteBuffer.allocateDirect(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过普通数组创建缓冲区：wrap(byte[] arr)</span></span><br><span class="line">        <span class="keyword">byte</span>[] arr = &#123;<span class="number">97</span>,<span class="number">98</span>,<span class="number">99</span>&#125;;</span><br><span class="line">        ByteBuffer buffer3 = ByteBuffer.wrap(arr);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="2-3-常用方法"><a href="#2-3-常用方法" class="headerlink" title="2.3 常用方法"></a>2.3 常用方法</h4><p>拿到一个缓冲区我们往往会做什么？很简单，就是<strong>读取缓冲区的数据/写数据到缓冲区中</strong>。</p>
<p>所以，缓冲区的核心方法就是:</p>
<ul>
<li>put(byte b) : 给数组添加元素</li>
<li>get() :获取一个元素</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo02Buffer</span>的方法 </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">//创建对象</span></span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//put(byte b) : 给数组添加元素</span></span><br><span class="line">    buffer.put((<span class="keyword">byte</span>)<span class="number">10</span>);</span><br><span class="line">    buffer.put((<span class="keyword">byte</span>)<span class="number">20</span>);</span><br><span class="line">    buffer.put((<span class="keyword">byte</span>)<span class="number">30</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//把缓冲数组变成普通数组</span></span><br><span class="line">    <span class="keyword">byte</span>[] arr = buffer.array();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打印</span></span><br><span class="line">    System.out.println(Arrays.toString(arr));</span><br><span class="line"></span><br><span class="line">    <span class="comment">//get() :获取一个元素</span></span><br><span class="line">    <span class="keyword">byte</span> b = buffer.get(<span class="number">1</span>);</span><br><span class="line">    System.out.println(b);   <span class="comment">//20</span></span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>Buffer类维护了4个核心变量属性来提供<strong>关于其所包含的数组的信息</strong>。它们是：</p>
<ul>
<li><p>容量Capacity</p>
</li>
<li><ul>
<li><strong>缓冲区能够容纳的数据元素的最大数量</strong>。容量在缓冲区创建时被设定，并且永远不能被改变。(不能被改变的原因也很简单，底层是数组嘛)</li>
</ul>
</li>
<li><p>界限Limit</p>
</li>
<li><ul>
<li><strong>缓冲区中可以操作数据的大小</strong>，代表了当前缓冲区中一共有多少数据（从limit开始后面的位置不能操作）。</li>
</ul>
</li>
<li><p>位置Position</p>
</li>
<li><ul>
<li><strong>下一个要被读或写的元素的位置</strong>。Position会自动由相应的 <code>get( )</code>和 <code>put( )</code>函数更新。</li>
<li>```<br>以上三个属性值之间有一些相对大小的关系：0 &lt;= position &lt;= limit &lt;= capacity<br>例：- 如果我们创建一个新的容量大小为20 的 ByteBuffer 对象，在初始化的时候，position 设置为 0，<br> limit 和 capacity 被设置为 10，在以后使用 ByteBuffer对象过程中，capacity 的值不会再发生变化，而其它两个个将会随着使用而变化。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">- 标记Mark</span><br><span class="line"></span><br><span class="line">- - 一个备忘位置。**用于记录上一次读写的位置**。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#### 2.4 buffer代码演示</span><br><span class="line"></span><br><span class="line">首先展示一下**是创建缓冲区后，核心变量的值是怎么变化的**</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line">public static void main(String[] args) &#123;</span><br><span class="line"></span><br><span class="line">        // 创建一个缓冲区</span><br><span class="line">        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);</span><br><span class="line"></span><br><span class="line">        // 看一下初始时4个核心变量的值</span><br><span class="line">        System.out.println(&quot;初始时--&gt;limit---&gt;&quot;+byteBuffer.limit());</span><br><span class="line">        System.out.println(&quot;初始时--&gt;position---&gt;&quot;+byteBuffer.position());</span><br><span class="line">        System.out.println(&quot;初始时--&gt;capacity---&gt;&quot;+byteBuffer.capacity());</span><br><span class="line">        System.out.println(&quot;初始时--&gt;mark---&gt;&quot; + byteBuffer.mark());</span><br><span class="line"></span><br><span class="line">        System.out.println(&quot;--------------------------------------&quot;);</span><br><span class="line"></span><br><span class="line">        // 添加一些数据到缓冲区中</span><br><span class="line">        String s = &quot;JavaEE&quot;;</span><br><span class="line">        byteBuffer.put(s.getBytes());</span><br><span class="line"></span><br><span class="line">        // 看一下初始时4个核心变量的值</span><br><span class="line">        System.out.println(&quot;put完之后--&gt;limit---&gt;&quot;+byteBuffer.limit());</span><br><span class="line">        System.out.println(&quot;put完之后--&gt;position---&gt;&quot;+byteBuffer.position());</span><br><span class="line">        System.out.println(&quot;put完之后--&gt;capacity---&gt;&quot;+byteBuffer.capacity());</span><br><span class="line">        System.out.println(&quot;put完之后--&gt;mark---&gt;&quot; + byteBuffer.mark());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<p>运行结果：</p>
<img src=".\img\image-20210305115457597.png" alt="image-20210305115457597" style="zoom:67%;" />



<p>现在<strong>我想要从缓存区拿数据</strong>，怎么拿呀？？NIO给了我们一个<code>flip()</code>方法。这个方法可以<strong>改动position和limit的位置</strong>！</p>
<p>还是上面的代码，我们<code>flip()</code>一下后，再看看4个核心属性的值会发生什么变化：</p>
<img src=".\img\image-20210305122308563.png" alt="image-20210305122308563" style="zoom:67%;" />



<p>很明显的是：</p>
<ul>
<li><strong>limit变成了position的位置了</strong></li>
<li><strong>而position变成了0</strong></li>
</ul>
<p>看到这里的同学可能就会想到了：当调用完<code>filp()</code>时：<strong>limit是限制读到哪里，而position是从哪里读</strong></p>
<p>一般我们称<code>filp()</code>为<strong>“切换成读模式”</strong></p>
<ul>
<li>每当要从缓存区的时候读取数据时，就调用<code>filp()</code><strong>“切换成读模式”</strong>。</li>
</ul>
<img src=".\img\image-20210304170527506.png" alt="image-20210304170527506" style="zoom:67%;" />

<p>切换成读模式之后，我们就可以读取缓冲区的数据了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个limit()大小的字节数组(因为就只有limit这么多个数据可读)</span></span><br><span class="line">      <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[byteBuffer.limit()];</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 将读取的数据装进我们的字节数组中</span></span><br><span class="line">      byteBuffer.get(bytes);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 输出数据</span></span><br><span class="line">      System.out.println(<span class="keyword">new</span> String(bytes, <span class="number">0</span>, bytes.length));</span><br></pre></td></tr></table></figure>

<p><img src=".%5Cimg%5Cimage-20210305121932875.png" alt="image-20210305121932875"></p>
<p>随后输出一下核心变量的值看看：</p>
<img src=".\img\image-20210305142054115.png" alt="image-20210305142054115" style="zoom:67%;" />



<p><strong>读完我们还想写数据到缓冲区</strong>，那就使用<code>clear()</code>函数，这个函数会“清空”缓冲区：</p>
<ul>
<li>数据没有真正被清空，只是被<strong>遗忘</strong>掉了</li>
</ul>
<img src=".\img\image-20210305143138279.png" alt="image-20210305143138279" style="zoom:67%;" />



<h2 id="3-Channel通道"><a href="#3-Channel通道" class="headerlink" title="3.Channel通道"></a>3.Channel通道</h2><h4 id="3-1-Channel通道概述"><a href="#3-1-Channel通道概述" class="headerlink" title="3.1 Channel通道概述"></a>3.1 Channel通道概述</h4><p>通道（Channel）：由 java.nio.channels 包定义 的。Channel 表示 IO 源与目标打开的连接。 </p>
<p>Channel 类似于传统的“<strong>流</strong>”。</p>
<p>标准的IO基于字节流和字符流进行操作的，而NIO是基于通道（Channel）和缓冲区（Buffer）进行操作，数据总是从通道读取到缓冲区中，或者从缓冲区写入到通道中（白话: 就是数据传输用的通道，作用是打开到IO设备的连接，文件、套接字都行）</p>
<p>例：相当于一根管子，buffer中的数据可以通过管子写入被操作的资源当中，也可以将资源通过管子写入到buffer中去</p>
<h4 id="3-2-Channel-API"><a href="#3-2-Channel-API" class="headerlink" title="3.2 Channel API"></a>3.2 Channel API</h4><p> Java 为 Channel 接口提供的最主要实现类如下： </p>
<img src=".\img\image-20210304173004802.png" alt="image-20210304173004802" style="zoom:67%;" />

<ul>
<li>FileChannel：用于读取、写入、映射和操作文件的通道。 </li>
<li>DatagramChannel：通过 UDP 读写网络中的数据通道。 </li>
<li>SocketChannel：通过 TCP 读写网络中的数据。 </li>
<li>ServerSocketChannel：可以监听新进来的 TCP 连接，对每一个新进来 的连接都会创建一个 SocketChannel。</li>
</ul>
<h4 id="3-3-FileChannel基本使用"><a href="#3-3-FileChannel基本使用" class="headerlink" title="3.3 FileChannel基本使用"></a>3.3 FileChannel基本使用</h4><ul>
<li>使用FileChannel完成文件的复制</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.buffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.FileInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.FileNotFoundException;</span><br><span class="line"><span class="keyword">import</span> java.io.FileOutputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.FileChannel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Channel</span>完成文件复制 </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通道依赖于IO流</span></span><br><span class="line">        <span class="comment">// 输入流 </span></span><br><span class="line">        FileInputStream fileInputStream = <span class="keyword">new</span> FileInputStream(<span class="string">&quot;C:\\Users\\sunzh\\Desktop\\wxy.png&quot;</span>);</span><br><span class="line">        <span class="comment">// 输出流</span></span><br><span class="line">        FileOutputStream fileOutputStream = <span class="keyword">new</span> 		FileOutputStream(<span class="string">&quot;C:\\Users\\sunzh\\Desktop\\lagou_myself\\nio\\复制.png&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用流获取通道</span></span><br><span class="line">        FileChannel f1 = fis.getChannel();</span><br><span class="line">        FileChannel f2 = fos.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建缓冲数组</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//循环</span></span><br><span class="line">        <span class="keyword">while</span>(f1.read(buffer) != -<span class="number">1</span>)&#123;</span><br><span class="line">            <span class="comment">//切换</span></span><br><span class="line">            buffer.flip();</span><br><span class="line">            <span class="comment">//输出</span></span><br><span class="line">            f2.write(buffer);</span><br><span class="line">            <span class="comment">//还原所有指针位置</span></span><br><span class="line">            buffer.clear();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关流</span></span><br><span class="line">        fos.close();</span><br><span class="line">        fis.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-4-网络编程收发信息"><a href="#3-4-网络编程收发信息" class="headerlink" title="3.4 网络编程收发信息"></a>3.4 网络编程收发信息</h4><ul>
<li><p>客户端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.buffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SocketChannel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span>客户端 </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建客户端</span></span><br><span class="line">        SocketChannel sc = SocketChannel.open();</span><br><span class="line">        <span class="comment">//指定要连接的服务器ip和端口</span></span><br><span class="line">        sc.connect(<span class="keyword">new</span> InetSocketAddress(<span class="string">&quot;127.0.0.1&quot;</span>,<span class="number">9000</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建缓冲输出</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//给数组添加数据</span></span><br><span class="line">        buffer.put(<span class="string">&quot;哈哈哈&quot;</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//切换</span></span><br><span class="line">        buffer.flip();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//输出数据</span></span><br><span class="line">        sc.write(buffer);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源</span></span><br><span class="line">        sc.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>服务器端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.buffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.ServerSocketChannel;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SocketChannel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span>服务端 </span>&#123;</span><br><span class="line">    <span class="comment">//阻塞的</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建服务端对象</span></span><br><span class="line">        ServerSocketChannel ssc = ServerSocketChannel.open();</span><br><span class="line">        <span class="comment">//绑定端口号</span></span><br><span class="line">        ssc.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">9000</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//连接客户端</span></span><br><span class="line">        SocketChannel sc = ssc.accept();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建缓冲数组</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//读取数据</span></span><br><span class="line">        <span class="keyword">int</span> len = sc.read(buffer);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打印</span></span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(buffer.array(),<span class="number">0</span>,len));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="3-5-accept阻塞问题"><a href="#3-5-accept阻塞问题" class="headerlink" title="3.5 accept阻塞问题"></a>3.5 accept阻塞问题</h4><ul>
<li><p>服务器端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.buffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.ServerSocketChannel;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SocketChannel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span>服务端非阻塞 </span>&#123;</span><br><span class="line">    <span class="comment">//阻塞的</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, InterruptedException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建服务端对象</span></span><br><span class="line">        ServerSocketChannel ssc = ServerSocketChannel.open();</span><br><span class="line">        <span class="comment">//绑定端口号</span></span><br><span class="line">        ssc.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">9000</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置非阻塞</span></span><br><span class="line">        ssc.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">//连接客户端</span></span><br><span class="line">            <span class="comment">//如果连接成功就是sc对象,如果没有连接就是sc=null</span></span><br><span class="line">            SocketChannel sc = ssc.accept();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//判断</span></span><br><span class="line">            <span class="keyword">if</span>(sc != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//创建缓冲数组</span></span><br><span class="line">                ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">                <span class="comment">//读取数据</span></span><br><span class="line">                <span class="keyword">int</span> len = sc.read(buffer);</span><br><span class="line"></span><br><span class="line">                <span class="comment">//打印</span></span><br><span class="line">                System.out.println(<span class="keyword">new</span> String(buffer.array(), <span class="number">0</span>, len));</span><br><span class="line"></span><br><span class="line">                <span class="comment">//结束循环</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                <span class="comment">//没有客户访问</span></span><br><span class="line">                <span class="comment">//在这里可以写别的业务代码</span></span><br><span class="line">                System.out.println(<span class="string">&quot;去忙点别的事儿...&quot;</span>);</span><br><span class="line">                Thread.sleep(<span class="number">3000</span>);</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="4-Selector选择器"><a href="#4-Selector选择器" class="headerlink" title="4.Selector选择器"></a>4.Selector选择器</h2><h4 id="3-1-多路复用的概念"><a href="#3-1-多路复用的概念" class="headerlink" title="3.1 多路复用的概念"></a>3.1 多路复用的概念</h4><p>​    一个选择器可以同时监听多个服务器端口, 帮多个服务器端口同时等待客户端的访问</p>
<h4 id="3-2-Selector的和Channel的关系"><a href="#3-2-Selector的和Channel的关系" class="headerlink" title="3.2 Selector的和Channel的关系"></a>3.2 Selector的和Channel的关系</h4><p>Channel和Buffer比较好理解 ，联系也比较密切，他们的关系简单来说就是：数据总是从通道中读到buffer缓冲区内，或者从buffer写入到通道中。</p>
<p><strong>选择器和他们的关系又是什么？</strong></p>
<p>选择器（Selector） 是 Channel（通道）的多路复用器，Selector 可以同时监控多个 通道的 IO（输入输出） 状况。</p>
<p><strong>Selector的作用是什么？</strong></p>
<p>选择器提供选择执行已经就绪的任务的能力。从底层来看，Selector提供了询问通道是否已经准备好执行每个I/O操作的能力。Selector 允许单线程处理多个Channel。仅用单个线程来处理多个Channels的好处是，只需要更少的线程来处理通道。事实上，可以只用一个线程处理所有的通道，这样会大量的减少线程之间上下文切换的开销。</p>
<h4 id="3-3-可选择通道-SelectableChannel"><a href="#3-3-可选择通道-SelectableChannel" class="headerlink" title="3.3 可选择通道(SelectableChannel)"></a>3.3 可选择通道(SelectableChannel)</h4><p>注意：并不是所有的Channel，都是可以被Selector 复用的。比方说，FileChannel就不能被选择器复用。为什么呢？</p>
<p>判断一个Channel 能被Selector 复用，有一个前提：判断他是否继承了一个抽象类SelectableChannel。如果继承了SelectableChannel，则可以被复用，否则不能。</p>
<p>SelectableChannle 的结构如下图：</p>
<img src=".\img\image-20210305163213213.png" alt="image-20210305163213213" style="zoom:80%;" />

<p>SelectableChannel类提供了实现通道的可选择性所需要的公共方法</p>
<p><strong>通道和选择器注册之后，他们是绑定的关系吗？</strong></p>
<p>答:不是。不是一对一的关系。一个通道可以被注册到多个选择器上，但对每个选择器而言只能被注册一次。</p>
<p>通道和选择器之间的关系，使用注册的方式完成。SelectableChannel可以被注册到Selector对象上，在注册的时候，需要指定通道的哪些操作，是Selector感兴趣的。</p>
<img src=".\img\image-20210305162501149.png" alt="image-20210305162501149" style="zoom:67%;" />





<h4 id="3-4-Channel注册到Selector"><a href="#3-4-Channel注册到Selector" class="headerlink" title="3.4 Channel注册到Selector"></a>3.4 Channel注册到Selector</h4><p>使用Channel.register（Selector sel，int ops）方法，将一个通道注册到一个选择器时。</p>
<p>​                                         第一个参数：指定通道要注册的选择器是谁</p>
<p>​                                         第二个参数：指定选择器需要查询的通道操作</p>
<p>可以供选择器查询的通道操作，从类型来分，包括以下四种：</p>
<p>​                                        （1）可读 : SelectionKey.OP_READ</p>
<p>​                                        （2）可写 : SelectionKey.OP_WRITE</p>
<p>​                                        （3）连接 : SelectionKey.OP_CONNECT</p>
<p>​                                        （4）接收 : SelectionKey.OP_ACCEPT</p>
<p>如果Selector对通道的多操作类型感兴趣，可以用“位或”操作符来实现：int key = SelectionKey.OP_READ | SelectionKey.OP_WRITE ;</p>
<h4 id="3-5-选择键-SelectionKey"><a href="#3-5-选择键-SelectionKey" class="headerlink" title="3.5 选择键(SelectionKey)"></a>3.5 选择键(SelectionKey)</h4><p>Channel和Selector的关系确定好后，并且一旦通道处于某种就绪的状态，就可以被选择器查询到。这个工作，使用选择器Selector的select（）方法完成。select方法的作用，对感兴趣的通道操作，进行就绪状态的查询。</p>
<p>Selector可以不断的查询Channel中发生的操作的就绪状态。并且挑选感兴趣的操作就绪状态。一旦通道有操作的就绪状态达成，并且是Selector感兴趣的操作，就会被Selector选中，放入选择键集合中。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">select()			:选择器等待客户端连接的方法</span><br><span class="line">					阻塞问题:</span><br><span class="line">						1.在开始没有客户访问的时候是阻塞的</span><br><span class="line">						2.在有客户来访问的时候方法会变成非阻塞的</span><br><span class="line">						3.如果客户的访问被处理结束之后,又会恢复成阻塞的</span><br><span class="line">						</span><br><span class="line">selectedKeys()		:选择器会把被连接的服务端对象放在Set集合中,这个方法就是返回一个Set集合</span><br></pre></td></tr></table></figure>



<h4 id="3-6-Selector的使用流程"><a href="#3-6-Selector的使用流程" class="headerlink" title="3.6 Selector的使用流程"></a>3.6 Selector的使用流程</h4><h5 id="3-6-1-创建Selector"><a href="#3-6-1-创建Selector" class="headerlink" title="3.6.1 创建Selector"></a>3.6.1 创建Selector</h5><p>Selector对象是通过调用静态工厂方法open()来实例化的，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1、获取Selector选择器</span></span><br><span class="line">        Selector selector = Selector.open();</span><br></pre></td></tr></table></figure>

<h5 id="3-6-2-将Channel注册到Selector"><a href="#3-6-2-将Channel注册到Selector" class="headerlink" title="3.6.2 将Channel注册到Selector"></a>3.6.2 将Channel注册到Selector</h5><p>要实现Selector管理Channel，需要将channel注册到相应的Selector上，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 2、获取通道</span></span><br><span class="line">    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.设置为非阻塞</span></span><br><span class="line">    serverSocketChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 4、绑定连接</span></span><br><span class="line">    serverSocketChannel.bind(<span class="keyword">new</span> InetSocketAddress(SystemConfig.SOCKET_SERVER_PORT));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 5、将通道注册到选择器上,并制定监听事件为：“接收”事件</span></span><br><span class="line">    serverSocketChannel.register(selector，SelectionKey.OP_ACCEPT);</span><br></pre></td></tr></table></figure>

<p>上面通过调用通道的register()方法会将它注册到一个选择器上。</p>
<p>首先需要注意的是：</p>
<p>与Selector一起使用时，Channel<strong>必须处于非阻塞模式</strong>下，否则将抛出异常IllegalBlockingModeException</p>
<h5 id="3-6-3-轮询查询就绪操作"><a href="#3-6-3-轮询查询就绪操作" class="headerlink" title="3.6.3 轮询查询就绪操作"></a>3.6.3 轮询查询就绪操作</h5><p>万事俱备，下一步是查询就绪的操作。</p>
<p>通过Selector的 select() 方法，可以查询出已经就绪的通道操作，这些就绪的状态集合，包存在一个元素是SelectionKey对象的Set集合中。</p>
<p>select()方法返回的int值，表示有多少通道已经就绪</p>
<p>而一旦调用select()方法，并且返回值不为0时，下一步工干啥？</p>
<p>通过调用Selector的selectedKeys()方法来访问已选择键集合，然后迭代集合的每一个选择键元素，根据就绪操作的类型，完成对应的操作：</p>
<h5 id="3-6-4-NIO-编程实例"><a href="#3-6-4-NIO-编程实例" class="headerlink" title="3.6.4 NIO 编程实例"></a>3.6.4 NIO 编程实例</h5><h6 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">       <span class="comment">//创建客户端</span></span><br><span class="line">       SocketChannel sc = SocketChannel.open();</span><br><span class="line">       <span class="comment">//指定要连接的服务器ip和端口</span></span><br><span class="line">       sc.connect(<span class="keyword">new</span> InetSocketAddress(<span class="string">&quot;127.0.0.1&quot;</span>,<span class="number">9000</span>));</span><br><span class="line"></span><br><span class="line">       <span class="comment">//创建缓冲输出</span></span><br><span class="line">       ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">       <span class="comment">//给数组添加数据</span></span><br><span class="line">       buffer.put(<span class="string">&quot;拉勾教育&quot;</span>.getBytes());</span><br><span class="line"></span><br><span class="line">       <span class="comment">//切换</span></span><br><span class="line">       buffer.flip();</span><br><span class="line"></span><br><span class="line">       <span class="comment">//输出数据</span></span><br><span class="line">       sc.write(buffer);</span><br><span class="line"></span><br><span class="line">       <span class="comment">//关闭资源</span></span><br><span class="line">       sc.close();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h6 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.selector;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SelectionKey;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.Selector;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.ServerSocketChannel;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span>服务端 </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//创建服务端对象</span></span><br><span class="line">        ServerSocketChannel ssc1 = ServerSocketChannel.open();</span><br><span class="line">        ssc1.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">8000</span>));</span><br><span class="line">        <span class="comment">//设置非阻塞</span></span><br><span class="line">        ssc1.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建服务端对象</span></span><br><span class="line">        ServerSocketChannel ssc2 = ServerSocketChannel.open();</span><br><span class="line">        ssc2.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">9000</span>));</span><br><span class="line">        ssc2.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建服务端对象</span></span><br><span class="line">        ServerSocketChannel ssc3 = ServerSocketChannel.open();</span><br><span class="line">        ssc3.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">10001</span>));</span><br><span class="line">        ssc3.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建选择器对象</span></span><br><span class="line">        Selector s = Selector.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//两个服务器都要交给选择器来管理</span></span><br><span class="line">        ssc1.register(s, SelectionKey.OP_ACCEPT);</span><br><span class="line">        ssc2.register(s, SelectionKey.OP_ACCEPT);</span><br><span class="line">        ssc3.register(s, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取集合</span></span><br><span class="line">        <span class="comment">//selectedKeys() :返回集合,集合作用存放的是被连接的服务对象的key</span></span><br><span class="line">        Set&lt;SelectionKey&gt; set = s.selectedKeys();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;集合中元素的个数: &quot;</span> + set.size());  <span class="comment">//0(没有服务端被访问的时候显示0)</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//select():这是选择器连接客户端的方法</span></span><br><span class="line">        s.select();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;集合中元素的个数: &quot;</span> + set.size());  <span class="comment">//1(有一个服务端被访问的时候显示1)</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lagou.selector;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SelectionKey;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.Selector;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.ServerSocketChannel;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.SocketChannel;</span><br><span class="line"><span class="keyword">import</span> java.util.Iterator;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Selector</span>服务端 </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 1、获取Selector选择器</span></span><br><span class="line">        Selector selector = Selector.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2、获取通道</span></span><br><span class="line">        ServerSocketChannel ssc1 = ServerSocketChannel.open();</span><br><span class="line">        ServerSocketChannel ssc2 = ServerSocketChannel.open();</span><br><span class="line">        ServerSocketChannel ssc3 = ServerSocketChannel.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.设置为非阻塞</span></span><br><span class="line">        ssc1.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">        ssc2.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">        ssc3.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 4、绑定连接</span></span><br><span class="line">        ssc1.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">8000</span>));</span><br><span class="line">        ssc2.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">9000</span>));</span><br><span class="line">        ssc3.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">10000</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 5、将通道注册到选择器上,并注册的操作为：&quot;接收&quot;操作</span></span><br><span class="line">        ssc1.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line">        ssc2.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line">        ssc3.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 6、采用轮询的方式，查询获取&quot;准备就绪&quot;的注册过的操作</span></span><br><span class="line">        <span class="keyword">while</span> (selector.select() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">// 7、获取当前选择器中所有注册的选择键（“已经准备就绪的操作”）</span></span><br><span class="line">            Iterator&lt;SelectionKey&gt; selectedKeys = selector.selectedKeys().iterator();</span><br><span class="line">            <span class="keyword">while</span> (selectedKeys.hasNext()) &#123;</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 8、获取&quot;准备就绪&quot;的事件</span></span><br><span class="line">                SelectionKey selectedKey = selectedKeys.next();</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// 9、获取ServerSocketChannel</span></span><br><span class="line">                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectedKey.channel();</span><br><span class="line">                <span class="comment">// 10、接受客户端发来的数据</span></span><br><span class="line">                SocketChannel socketChannel = serverSocketChannel.accept();</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 11、读取数据</span></span><br><span class="line">                    ByteBuffer byteBuffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">                    <span class="keyword">int</span> length = <span class="number">0</span>;</span><br><span class="line">                    <span class="keyword">while</span> ((length = socketChannel.read(byteBuffer)) != -<span class="number">1</span>) &#123;</span><br><span class="line">                        byteBuffer.flip();</span><br><span class="line">                        System.out.println(<span class="keyword">new</span> String(byteBuffer.array(), <span class="number">0</span>, length));</span><br><span class="line">                        byteBuffer.clear();</span><br><span class="line">                    &#125;</span><br><span class="line">                    socketChannel.close();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 12、移除选择键</span></span><br><span class="line">                selectedKeys.remove();</span><br><span class="line">            &#125;</span><br><span class="line">        <span class="comment">// 13、关闭连接</span></span><br><span class="line">       	 ssc1.close();</span><br><span class="line">       	 ssc2.close();</span><br><span class="line">      	 ssc3.close();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





    </div>

    
    
    

    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2021/08/15/NIO/">NIO学习笔记</a></p>
  <p><span>文章作者:</span><a href="/" title="访问  的个人博客"></a></p>
  <p><span>发布时间:</span>2021年08月15日 - 00:08</p>
  <p><span>最后更新:</span>2021年08月15日 - 17:08</p>
  <p><span>原始链接:</span><a href="/blog/2021/08/15/NIO/" title="NIO学习笔记">http://shu_kang.gitee.io/2021/08/15/NIO/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://shu_kang.gitee.io/2021/08/15/NIO/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>



      
    </div>
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/wxpay.jpg" alt="Shuker 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/alipay.jpg" alt="Shuker 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/IO%E6%B5%81/" rel="tag"># IO流</a>
              <a href="/blog/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" rel="tag"># 网络编程</a>
          </div>

        


        
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=32408691&auto=1&height=66"></iframe>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#NIO"><span class="nav-number">1.</span> <span class="nav-text">NIO</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFNIO"><span class="nav-number">1.1.</span> <span class="nav-text">1. 什么是NIO</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#IO%E5%9B%9E%E9%A1%BE"><span class="nav-number">1.1.0.1.</span> <span class="nav-text">IO回顾</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-%E6%A6%82%E5%BF%B5"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">1.1 概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-%E4%BD%9C%E7%94%A8"><span class="nav-number">1.1.0.3.</span> <span class="nav-text">1.2 作用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-%E6%B5%81%E4%B8%8E%E5%9D%97%E7%9A%84%E6%AF%94%E8%BE%83"><span class="nav-number">1.1.0.4.</span> <span class="nav-text">1.3 流与块的比较</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4-%E6%96%B0%E7%89%B9%E6%80%A7"><span class="nav-number">1.1.0.5.</span> <span class="nav-text">1.4 新特性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-5-%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6"><span class="nav-number">1.1.0.6.</span> <span class="nav-text">1.5 核心组件</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Buffer%E7%BC%93%E5%86%B2%E5%8C%BA"><span class="nav-number">1.2.</span> <span class="nav-text">2. Buffer缓冲区</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-Buffer%E7%BC%93%E5%86%B2%E5%8C%BA%E6%A6%82%E8%BF%B0"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">2.1 Buffer缓冲区概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-ByteBuffer%E7%9A%84%E5%88%9B%E5%BB%BA%E6%96%B9%E5%BC%8F"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">2.2 ByteBuffer的创建方式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">2.3 常用方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-Channel%E9%80%9A%E9%81%93"><span class="nav-number">1.3.</span> <span class="nav-text">3.Channel通道</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-Channel%E9%80%9A%E9%81%93%E6%A6%82%E8%BF%B0"><span class="nav-number">1.3.0.1.</span> <span class="nav-text">3.1 Channel通道概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-Channel-API"><span class="nav-number">1.3.0.2.</span> <span class="nav-text">3.2 Channel API</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-FileChannel%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="nav-number">1.3.0.3.</span> <span class="nav-text">3.3 FileChannel基本使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E6%94%B6%E5%8F%91%E4%BF%A1%E6%81%AF"><span class="nav-number">1.3.0.4.</span> <span class="nav-text">3.4 网络编程收发信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-accept%E9%98%BB%E5%A1%9E%E9%97%AE%E9%A2%98"><span class="nav-number">1.3.0.5.</span> <span class="nav-text">3.5 accept阻塞问题</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-Selector%E9%80%89%E6%8B%A9%E5%99%A8"><span class="nav-number">1.4.</span> <span class="nav-text">4.Selector选择器</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">3.1 多路复用的概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-Selector%E7%9A%84%E5%92%8CChannel%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">3.2 Selector的和Channel的关系</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-%E5%8F%AF%E9%80%89%E6%8B%A9%E9%80%9A%E9%81%93-SelectableChannel"><span class="nav-number">1.4.0.3.</span> <span class="nav-text">3.3 可选择通道(SelectableChannel)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-Channel%E6%B3%A8%E5%86%8C%E5%88%B0Selector"><span class="nav-number">1.4.0.4.</span> <span class="nav-text">3.4 Channel注册到Selector</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-%E9%80%89%E6%8B%A9%E9%94%AE-SelectionKey"><span class="nav-number">1.4.0.5.</span> <span class="nav-text">3.5 选择键(SelectionKey)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-6-Selector%E7%9A%84%E4%BD%BF%E7%94%A8%E6%B5%81%E7%A8%8B"><span class="nav-number">1.4.0.6.</span> <span class="nav-text">3.6 Selector的使用流程</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-1-%E5%88%9B%E5%BB%BASelector"><span class="nav-number">1.4.0.6.1.</span> <span class="nav-text">3.6.1 创建Selector</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-2-%E5%B0%86Channel%E6%B3%A8%E5%86%8C%E5%88%B0Selector"><span class="nav-number">1.4.0.6.2.</span> <span class="nav-text">3.6.2 将Channel注册到Selector</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-3-%E8%BD%AE%E8%AF%A2%E6%9F%A5%E8%AF%A2%E5%B0%B1%E7%BB%AA%E6%93%8D%E4%BD%9C"><span class="nav-number">1.4.0.6.3.</span> <span class="nav-text">3.6.3 轮询查询就绪操作</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-6-4-NIO-%E7%BC%96%E7%A8%8B%E5%AE%9E%E4%BE%8B"><span class="nav-number">1.4.0.6.4.</span> <span class="nav-text">3.6.4 NIO 编程实例</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="nav-number">1.4.0.6.4.1.</span> <span class="nav-text">客户端</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="nav-number">1.4.0.6.4.2.</span> <span class="nav-text">服务端</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Shuker"
      src="https://pic1.zhimg.com/50/v2-e6c265da0c4d51976b5a4f5789bf1930_qhd.jpg?source=ba7200d9">
  <p class="site-author-name" itemprop="name">Shuker</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">1</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/yourname" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://plus.google.com/yourname" title="Google → https:&#x2F;&#x2F;plus.google.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-google fa-fw"></i>Google</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://twitter.com/yourname" title="Twitter → https:&#x2F;&#x2F;twitter.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-twitter fa-fw"></i>Twitter</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Shuker</span>
</div>

<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div> 
-->
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共4.9k字</span>
</div>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
<!-- ҳ����С���� -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
<!-- ӣ��Ʈ��Ч�� -->
<script type="text/javascript" src="/js/src/sakura.js"></script>
